﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ARS.Control.Attributes;
using ARS.Control.Custom.SelectLinkage.Attributes;
using ARS.Control.Factory;
using ARS.DataBase.Provider;

namespace ARS.Control.Custom.SelectLinkage.Widget
{
    /// <summary>
    /// 联动选择
    /// </summary>
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:SelectLinkage runat=server></{0}:SelectLinkage>")]
    public class SelectLinkage :WebControl
    {
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Text
        {
            get
            {
                String s = (String)ViewState["Text"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["Text"] = value;
            }
        }


        public static string GetSqlIndex(ref string dbSelectSLList, int index)
        {
            return dbSelectSLList.Split(new[] { Const.OPERATLISTDELIMITER }, StringSplitOptions.None)[index];
        }

        private string _DbSelectSLList;
        public string DbSelectSLList
        {
            get
            {
                if (_DbSelectSLList == null)
                {
                    if (DbSelectSLListItem != null)
                    {
                        System.Text.StringBuilder sb = new StringBuilder();
                        foreach (DbSelectSL dss in DbSelectSLListItem)
                        {
                            sb.Append(dss.GetSelectAllSql());
                            sb.Append(Const.OPERATLISTDELIMITER);
                        }
                        _DbSelectSLList = sb.ToString();
                    }
                }
                return _DbSelectSLList;
            }
            set
            {
                _DbSelectSLList = value;
            }
        }

        public DbSelectSL[] DbSelectSLListItem
        {
            get;
            set;
        }

        public DropDownList[] DropDownListItem
        {
            get;
            set;
        }

        //选择值
        public string[] valueList { get; set; }

        private string _ParentNameFieldList;
        public string ParentNameFieldList
        {
            get
            {
                if (_ParentNameFieldList == null)
                {

                }
                return _ParentNameFieldList;
            }
        }

        private string _DataValueFieldList;
        public string DataValueFieldList
        {
            get
            {
                return _DataValueFieldList;
            }
        }

        private string _DataTextFieldList;

        public string DataTextFieldList
        {
            get
            {
                return _DataTextFieldList;
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            this.Page.ClientScript.RegisterClientScriptResource(typeof(SelectLinkage), ResourcePath.SelectLinkage.js);
            base.OnPreRender(e);
        }

        /// <summary>
        /// 插入行
        /// </summary>
        /// <param name="value"></param>
        /// <param name="text"></param>
        /// <param name="index"></param>
//        public void AddDtRow(DataTable dataTable, string value, string text, int index)
//        {
//            if (dataTable != null)
//            {
//                System.Data.DataRow dr = dataTable.NewRow();

//            }
//        }

        public string FirstOptionTextList { get; set; }

        public string FirstOptionValueList { get; set; }
        /// <summary>
        /// 加载回传的值
        /// </summary>
        public void InitLastValue()
        {
            if ((HttpContext.Current.Request.HttpMethod == "POST"))
            {
                List<string> list = new List<string>();
                for (int i = 0; i < this.DbSelectSLListItem.Count(); i++)
                {
                    list.Add(HttpContext.Current.Request.Form["SelectLinkage" + (i).ToString()]);
                }
                this.valueList = list.ToArray();
            }
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            if (DbSelectSLListItem != null)
            {

                DataBase.Provider.IDataPagingProvider dataProvider = ARS.DataBase.Provider.DataPagingProvider.GetInstance();
                //DataTable lastDT = null;
                string lastKey=null;
                //bool isFist = true;
                int count = DbSelectSLListItem.Length;
                int index = 0;
                foreach (DbSelectSL dss in DbSelectSLListItem)
                {
                    //设置要保存的值

                    _ParentNameFieldList += dss.ParentNameField + Const.OPERATLISTDELIMITER;
                    _DataValueFieldList += dss.DataValueField + Const.OPERATLISTDELIMITER;
                    _DataTextFieldList += dss.DataTextField + Const.OPERATLISTDELIMITER;

                    _DbSelectSLList += dss.GetSelectAllSql() + Const.OPERATLISTDELIMITER;

                    this.FirstOptionValueList+=dss.FirstOptionValue+ Const.OPERATLISTDELIMITER;
                    this.FirstOptionTextList += dss.FirstOptionText + Const.OPERATLISTDELIMITER;
                    //ARS.Control.Attributes.DbSelectAll sda = (ARS.Control.Attributes.DbSelectAll) dss;
                    DataTable dt;
                    if (index==0)
                    {
                        dt = dataProvider.GetDataList(dss).Tables[0];
                    }                    
                    else
                    {
                        dss.StrWhere += string.Format(" and {0}={1}", dss.ParentNameField, lastKey);
                        dt = dataProvider.GetDataList(dss).Tables[0];
                    }
                    if (dss.FirstOptionText != null)
                    {
                        System.Data.DataRow dr = dt.NewRow();
                        dr[dss.DataValueField] = dss.FirstOptionValue;
                        dr[dss.DataTextField] = dss.FirstOptionText;
                        dt.Rows.InsertAt(dr, 0);
                    }

                    DropDownList ddl = new DropDownList();
                    if (index < count - 1)
                    {
                        ddl.Attributes.Add("onchange", string.Format("sl_change(this,{0})",index));
                    }
                    ddl.DataSource = dt;
                    ddl.DataTextField = dss.DataTextField;
                    ddl.DataValueField = dss.DataValueField;
                    ddl.CssClass = dss.Css;

                    ddl.ID = "SelectLinkage"+index.ToString();
                    ddl.DataBind();
                    if (valueList != null)
                    {
                        if (valueList.Count() > index)
                        {
                            try
                            {
                                ddl.SelectedValue = valueList[index];
                            }
                            catch (Exception)
                            {
                                
                                //throw;
                            }
                        }
                    }
                    ddl.RenderControl(output);

                    if (dt.Rows.Count > 0)
                    {
                        lastKey = ddl.SelectedValue;                       
                    }
                    else
                    {
                        break;
                    }
                    index++;


                }

                ARS.DataBase.Provider.IDbProvider dbProvider = DataBase.Provider.DbProvider.GetInstance();
                Interface.IUser user = UserFactory.CreateUser();
                string userId = user.GetUserInfo().Id.ToString();
                dbProvider.ExecuteSql(string.Format("delete from ARS_SelectLinkage where Users_Id={0};insert into ARS_SelectLinkage(Users_Id,DbSelectSLList,ParentNameFieldList,DataValueFieldList,DataTextFieldList,FirstOptionValueList,FirstOptionTextList) values({0},'{1}','{2}','{3}','{4}','{5}','{6}')", userId, this.DbSelectSLList, this.ParentNameFieldList, this.DataValueFieldList, this.DataTextFieldList,this.FirstOptionValueList,this.FirstOptionTextList));
            }

            
        }

        public string GetInputValue()
        {
            return HttpContext.Current.Request.Form["SelectLinkage" + (this.DbSelectSLListItem.Count()-1).ToString()];
        }
        public string GetInputValue(int index)
        {
            return HttpContext.Current.Request.Form["SelectLinkage" + (index).ToString()];
        }

//        private void ddl_Load(object sender, EventArgs e)
//        {
//            DropDownList ddl = (DropDownList) sender;
//            ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue(valueList[index]));
//        }
    }
}
